package com.example.utils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

import android.os.Environment;

import com.example.model.Mp3Info;

/**
 * Provides functions including creating file, getting files on SD card, creating folder on SD card and 
 * checking if file exists.
 * 
 * @author congwang
 *
 */
public class FileUtils {
	private String SDPATH;

	public String getSDPATH() {
		return SDPATH;
	}
	
	/**
	 * Get SD card path.
	 */
	public FileUtils() {
		SDPATH = Environment.getExternalStorageDirectory() + "/";
	}
	/**
	 * Create new file.
	 * @throws IOException
	 */
	public File creatSDFile(String fileName) throws IOException {
		File file = new File(SDPATH + fileName);
		file.createNewFile();
		return file;
	}
	
	/**
	 * Create a directory on SD card.
	 * @param dirName
	 */
	public File creatSDDir(String dirName) {
		File dir = new File(SDPATH + dirName);
		dir.mkdirs();
		return dir;
	}

	/**
	 * if specified file exists.
	 */
	public boolean isFileExist(String fileName){
		File file = new File(SDPATH + fileName);
		return file.exists();
	}
	
	/**
	 * Write file into SD card.
	 */
	public File write2SDFromInput(String path,String fileName,InputStream input){
		File file = null;
		OutputStream output = null;
		try{
			creatSDDir(path);
			file = creatSDFile(path + fileName);
			output = new FileOutputStream(file);
			byte buffer [] = new byte[4 * 1024];
			int temp = 0;
			while((temp = input.read(buffer)) != -1){
				output.write(buffer, 0, temp);
			}
			output.flush();
		}
		catch(Exception e){
			e.printStackTrace();
		}
		finally{
			try{
				output.close();
			}
			catch(Exception e){
				e.printStackTrace();
			}
		}
		return file;
	}
	
	/**
	 * Get all files from specified folder.
	 * 
	 * @param folderPath
	 * @return
	 */
	public List<Mp3Info> getMp3Files(String folderPath) {
		List<Mp3Info> mp3Infos = new ArrayList<Mp3Info>();
		File file = new File(SDPATH + File.separator + folderPath);
		File[] files = file.listFiles();
		for (File f: files) {
			if (!f.getName().endsWith(".mp3")) {
				continue;
			}
			Mp3Info mp3Info = new Mp3Info();
			mp3Info.setMp3Name(f.getName());
			mp3Info.setMp3Size(f.length() + "");
			mp3Infos.add(mp3Info);
		}
		
		return mp3Infos;
	}

}